package com.cdc.taskhandler;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * Created by cdc on 2018/3/26.
 */

public class DownFile {

    private static final String  TAG="DownFile";
    private String urlStr;

    public DownFile(String urlStr) {
        this.urlStr = urlStr;
    }

    public Bitmap getBitmap(){
        Bitmap bitmap=null;
        HttpURLConnection httpURLConnection=null;
        InputStream inputStream=null;
        BufferedInputStream bis=null;
        try {
            URL url=new URL(urlStr);
            httpURLConnection= (HttpURLConnection) url.openConnection();
            String type=httpURLConnection.getContentType();
            String length=httpURLConnection.getContentLength()+"";
            Log.i(TAG,"type="+type+",length="+length);
            Map<String,List<String>> maps= httpURLConnection.getHeaderFields();
            for (Map.Entry<String, List<String>> stringListEntry : maps.entrySet()) {
                List<String>  values=stringListEntry.getValue();
                for (String value : values) {
                    Log.i(TAG,"key="+stringListEntry.getKey()+",value="+value);
                }
            }
            inputStream=httpURLConnection.getInputStream();
            bis=new BufferedInputStream(inputStream);
            bitmap= BitmapFactory.decodeStream(bis);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(httpURLConnection!=null){
                httpURLConnection.disconnect();
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bitmap;
    }


}

